package lc.q300_350;

import java.util.*;

public class Q350 {

    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        Map<Integer, Integer> map1 = new HashMap<>();
        for (int i : nums1) {
            map1.put(i, map1.getOrDefault(i, 0) + 1);
        }
        int[] result = new int[nums2.length];
        int index = 0;
        for (int i : nums2) {
            Integer times = map1.getOrDefault(i, 0);
            if (times > 0) {
                result[index] = i;
                map1.put(i, times - 1);
                index ++;
            }
        }
        return Arrays.copyOfRange(result, 0, index);
    }
}
